<script setup>
import {
    Edit,
    Delete
} from '@element-plus/icons-vue'

import { ref } from 'vue'

//获取到的用户数据    展示个样例，可以删去
const users = ref([
    {
        "id": 3,
        "username": "22222",
        "nickname": "2b",
        "email": "2965079649@qq.com",
        "userPic": "https://enlongwu.oss-cn-guangzhou.aliyuncs.com/e9611242-150d-4799-be97-09c34422eaf9.jpg",
        "createTime": "2024-03-16T16:39:52",
        "updateTime": "2024-03-16T16:41:08",
        "role": "initial"
    }
])


import useSystemParameter from '@/stores/useSystemParameter';
const systemParameter = useSystemParameter();
// const roles = ref()
// roles.value = rolesStore.info;
// console.log(roles.value)



const searchRole = ref('')
//用户搜索
const searchString = ref('')

//分页条数据模型
const pageNum = ref(1)//当前页
const total = ref()//总条数
const pageSize = ref(3)//每页条数

//当每页条数发生了变化，调用此函数
const onSizeChange = (size) => {
    pageSize.value = size
    userList()
}
//当前页码发生变化，调用此函数
const onCurrentChange = (num) => {
    pageNum.value = num
    userList()
}


import { userListService } from '@/api/user.js';
//获取用户列表数据
const userList = async () => {
    let params = {
        pageNum: pageNum.value,
        pageSize: pageSize.value,
        searchString: searchString.value ? searchString.value : null,
        role: searchRole.value ? searchRole.value : null
    }
    let result = await userListService(params);
    //渲染到视图上
    total.value = result.data.total;
    users.value = result.data.items;

    if (result.status === 1) {
        ElMessage.error(result.message ? result.message : "查找失败")
    } else if (result.data.total === 0) {
        ElMessage.error("没有符合条件的信息");
    }
    console.log("共查询到" + result.data.total + "条信息");
}
userList();


// 在 Vue 3 中使用 Element Plus 的对话框
import { ElMessageBox } from 'element-plus';




// //获取文章分类
// const articleCategoryList = async () => {
//     //调用接口，获取动态数据库中的文章列表数据
//     let result = await articleCategoryListService();
//     categorys.value = result.data;
// }
// articleCategoryList()


import { Plus } from '@element-plus/icons-vue'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
//导入token
import { useTokenStore } from '@/stores/token.js'
const tokenStore = useTokenStore();
import { ArticleAddService } from '@/api/article.js';
import { ElMessage } from 'element-plus';
import avatar from '@/assets/default.png'
//控制抽屉是否显示
const visibleDrawer = ref(false)
//注册信息
const registerData = ref({
    username: '',
    password: '123456',
    role: 'initial',
    nickname: '',
    email: ''
})
//定义表单校验规则
const rules = {
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 5, max: 16, message: '长度为5~16位非空字符', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 5, max: 16, message: '长度为5~16位非空字符', trigger: 'blur' }
    ],
    nickname: [
        { required: false, message: '请输入用户昵称', trigger: 'blur' },
        {
            // pattern: /^\S{2,10}$/,
            message: '昵称必须是2-10位的非空字符串',
            trigger: 'blur'
        }
    ],
    email: [
        { required: false, message: '请输入用户邮箱', trigger: 'blur' },
        { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
    ]

}
//上传成功的回调函数
const uploadSuccess = (result) => {
    registerData.value.userPic = result.data;
    console.log(result.data);
}

import { userRegisterService } from '@/api/user.js'
//调用后台接口完成注册
const register = async () => {
    // registerData是响应式对象，需要.value才能获取值
    let result = await userRegisterService(registerData.value);
    //见request响应拦截器，对失败进行处理了
    // if(result.code===0){
    //     //成功了
    //     alert(result.data?result.data:'注册成功！');
    // }else{
    //     //失败了
    //     alert(result.message+' 注册失败!');
    // }
    ElMessage.success(result.data ? result.data : '注册成功！');
    //让抽屉消失
    visibleDrawer.value = false;
    registerData.value = {//重置默认数据
        username: '',
        password: '123456',
        role: 'initial'
    }
    //刷新当前列表
    userList();
}





//设置
const isShowMore = ref(false);
const isConfirm = ref(false);//删

import { userInfoUpdateService } from '@/api/user.js';

const userInfoStore = useUserInfoStore()
//更改用户
const updateUser = async (userInfo) => {
    let result = await userInfoUpdateService(userInfo);
    console.log(result)
    if (result.code === 0) {
        ElMessage.success(result)
    } else {
        ElMessage.error(result)
    }
    console.log(userInfoStore.info)
    userList();//刷新展示列表
    userInfoStore.countUnread();
}

//edit
const dialogVisible = ref(false);
//定义变量控制标题的展示
const title = ref('')
const editUser = ref(
    {
        "id": '',
        "username": "",
        "nickname": "",
        "email": "",
        "userPic": "",
        "createTime": "",
        "updateTime": "",
        "role": ""
    }
)
//展示编辑表单弹窗并获取数据
const showEditForm = (row) => {
    dialogVisible.value = true;
    title.value = '编辑用户信息';
    console.log(row);
    // editUser.value = row;
    editUser.value.username = row.username;
    editUser.value.nickname = row.nickname;
    editUser.value.email = row.email;
    editUser.value.userPic = row.userPic;
    editUser.value.role = row.role;

    editUser.value.id = row.id;
    console.log('展示数据id:' + row.id);
}
//图片上传成功的回调函数
const uploadSuccess_edit = (result) => {
    editUser.value.userPic = result.data;
    console.log(editUser.value.userPic);
}

//修改密码框
const dialogVisible_psw = ref(false);
const params_psw = ref(
    {
        "id": '',
        "newPwd": ""
    }
)
//展示修改密码表单并获取数据
const showUpdatePswForm = (row) => {
    dialogVisible_psw.value = true;
    title.value = '修改用户密码';
    params_psw.value.id = row.id;//传给后端
    params_psw.value.newPwd = "";//清空待写
    //展示出来
    editUser.value.username = row.username;
    editUser.value.nickname = row.nickname;
    editUser.value.email = row.email;
    editUser.value.userPic = row.userPic;
    editUser.value.role = row.role;
}
import { updatePswService } from '@/api/user.js'
import useUserInfoStore from '@/stores/userInfo';
//修改密码
const updateUserPsw = async (params) => {
    if (params.newPwd.length >= 5 && params.newPwd.length <= 16) {
        let result = await updatePswService(params);//参数也就是params_psw
        if (result.code === 0) {
            ElMessage.success(result);
            dialogVisible_psw.value = false;
        } else {
            dialogVisible_psw.value = true;
        }
    } else {
        ElMessage.error('请输入5至16位新密码');
        dialogVisible_psw.value = true;
    }
}




</script>

<template >

    <el-card class="page-container" :enable="false">
        <template #header>
            <div class="header">
                <span>用户权限管理</span>
                <div class="extra">
                    <el-button type="primary" @click="visibleDrawer = true">注册用户</el-button>
                </div>
            </div>
        </template>
        <!-- 搜索表单 -->
        <el-form inline>
            <el-form-item label="用户权限：">
                <el-select placeholder="所有" v-model="searchRole" style="width: 200px;">
                    <el-option v-for="c in systemParameter.roles" :key="c.role" :label="c.roleName" :value="c.role" @click="userList()">
                    </el-option>
                    <el-option label="所有" value="" @click="userList()">
                    </el-option>
                </el-select>
            </el-form-item>

            <el-form-item label="模糊匹配：">
                <el-input v-model="searchString" style="width: 240px" placeholder="请输入" clearable
                    @change="userList();" />
            </el-form-item>
            <el-form-item>详细：<el-switch v-model="isShowMore" /></el-form-item>
        </el-form>

        <!-- 用户列表 -->
        <el-table :data="users" style="width: 100%">
            <el-table-column label="用户名" prop="username"></el-table-column>
            <el-table-column label="昵称" prop="nickname"></el-table-column>
            <el-table-column label="邮箱" prop="email"> </el-table-column>
            <el-table-column label="头像" prop="userPic" v-if="isShowMore">
                <template #default="{ row }">
                    <el-upload ref="uploadRef" class="avatar-show" :show-file-list="false" :auto-upload="false"
                        action="/api/upload" name="file" :headers="{ 'Authorization': tokenStore.token }"
                        :on-success="uploadSuccess">
                        <img :src="row.userPic ? row.userPic : avatar" class="avatar" />
                    </el-upload>
                </template>
            </el-table-column>
            <el-table-column label="注册时间" prop="createTime" v-if="isShowMore"></el-table-column>
            <el-table-column label="更新时间" prop="updateTime" v-if="isShowMore"></el-table-column>
            <el-table-column label="权限" prop="role">
                <template #default="{ row }">
                    <div style="margin-top:">
                        <el-radio-group v-model="row.role" size="small" :class="{ 'custom-radio': true }">
                            <el-radio v-for="c in systemParameter.roles" :label='c.roleName' :value="c.role" @change="updateUser(row)"
                                :class="{ 'custom-radio': true }"></el-radio>
                        </el-radio-group>
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="100">
                <template #default="{ row }">
                    <!-- <el-button :icon="Edit" circle plain type="primary" @click="showEditForm(row)"></el-button> -->
                    <el-button circle plain type="primary" class="button-with-image" @click="showEditForm(row)">
                        <img src="@/assets/editUser_black.png" alt="icon" class="button-image" />
                    </el-button>
                    <el-button circle plain type="primary" class="button-with-image" @click="showUpdatePswForm(row)">
                        <img src="@/assets/updatePsw.png" alt="icon" class="button-image" />
                    </el-button>

                </template>
            </el-table-column>
            <template #empty>
                <el-empty description="没有数据" />
            </template>
        </el-table>
        <!-- 分页条 -->
        <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[3, 5, 10, 15]"
            layout="jumper, total, sizes, prev, pager, next" background :total="total" @size-change="onSizeChange"
            @current-change="onCurrentChange" style="margin-top: 20px; justify-content: flex-end" />
        <!-- 抽屉 -->
        <el-drawer v-model="visibleDrawer" title="注册账户" direction="rtl" size="50%">
            <!-- 添加表单 -->
            <el-form :model="registerData" label-width="100px" :rules="rules">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="registerData.username" placeholder="请输入用户名"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="registerData.password" placeholder="请输入密码"></el-input>
                </el-form-item>
                <el-form-item label="昵称" prop="nickname">
                    <el-input v-model="registerData.nickname" placeholder="请输入昵称"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="registerData.email" placeholder="请输入昵称"></el-input>
                </el-form-item>
                <el-form-item label="赋予权限">
                    <el-select placeholder="请选择" v-model="registerData.role">
                        <el-option v-for="c in systemParameter.roles" :key="c.id" :label="c.roleName" :value="c.role">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="用户头像">
                    <!-- auto-upload:设置是否自动上传
    action：设置服务器接口路径，注意解决跨域问题
    name：设置上传的文件字段名
    headers：设置上传的请求头
    on-success:设置上传成功的回调函数 -->
                    <el-upload class="avatar-uploader" :auto-upload="true" :show-file-list="false" action="/api/upload"
                        name="file" :headers="{ 'Authorization': tokenStore.token }" :on-success="uploadSuccess">
                        <img v-if="registerData.userPic" :src="registerData.userPic" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" @click="register">注册</el-button>
                    <!-- <el-button type="info" @click="addArticle('草稿')">草稿</el-button> -->
                </el-form-item>
            </el-form>
        </el-drawer>

        <!-- 详细信息修改表单 -->
        <el-dialog v-model="dialogVisible" :title='title' width="30%">
            <el-form :model="editUser" :rules="rules" label-width="100px" style="padding-right: 30px">
                <el-form-item label="用户名">
                    <el-input v-model="editUser.username" disabled></el-input>
                </el-form-item>
                <el-form-item label="昵称" prop="nickname">
                    <el-input v-model="editUser.nickname" minlength="1" maxlength="10"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="editUser.email" minlength="1" maxlength="15"></el-input>
                </el-form-item>
                <el-form-item label="头像" prop="userPic">
                    <el-upload ref="uploadRef" class="avatar-show" :show-file-list="false" :auto-upload="true"
                        action="/api/upload" name="file" :headers="{ 'Authorization': tokenStore.token }"
                        :on-success="uploadSuccess_edit">
                        <img :src="editUser.userPic ? editUser.userPic : avatar" class="avatar" />
                    </el-upload>
                </el-form-item>
                <el-form-item label="权限">
                    <el-select placeholder="请选择" v-model="editUser.role" style="width: 200px;">
                        <el-option v-for="c in systemParameter.roles" :key="c.role" :label="c.roleName" :value="c.role">
                        </el-option>
                    </el-select>
                </el-form-item>

            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="updateUser(editUser), dialogVisible = false"> 确认
                    </el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 密码修改表单 -->
        <el-dialog v-model="dialogVisible_psw" :title='title' width="30%">
            <el-form :model="editUser" :rules="rules" label-width="100px" style="padding-right: 30px">
                <el-form-item label="用户名">
                    <el-input v-model="editUser.username" disabled></el-input>
                </el-form-item>

                <el-form-item label="新密码" prop="password">
                    <el-input v-model="params_psw.newPwd" minlength="5" maxlength="16"></el-input>
                </el-form-item>

            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible_psw = false">取消</el-button>
                    <el-button type="primary" @click="updateUserPsw(params_psw)"> 确认
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </el-card>






</template>
<style lang="scss" scoped>
.page-container {
    min-height: 100%;
    box-sizing: border-box;

    .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
}

.avatar-show {
    :deep() {
        .avatar {
            width: 50px;
            height: 50px;
            display: block;
        }

        .el-upload {
            border: 1px dashed var(--el-border-color);
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
            transition: var(--el-transition-duration-fast);
        }

        .el-upload:hover {
            border-color: var(--el-color-primary);
        }

        .el-icon.avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 178px;
            height: 178px;
            text-align: center;
        }
    }
}

//多选样式
.custom-radio {
    width: 40px;
    /* 设置按钮的固定宽度，可以根据需要调整 */
}

/* 抽屉样式 */
.avatar-uploader {
    :deep() {
        .avatar {
            width: 178px;
            height: 178px;
            display: block;
        }

        .el-upload {
            border: 1px dashed var(--el-border-color);
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
            transition: var(--el-transition-duration-fast);
        }

        .el-upload:hover {
            border-color: var(--el-color-primary);
        }

        .el-icon.avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 178px;
            height: 178px;
            text-align: center;
        }
    }
}

.editor {
    width: 100%;

    :deep(.ql-editor) {
        min-height: 200px;
    }
}


//图像按钮
.button-with-image {
    position: relative;
    /* 确保按钮内部的定位基于按钮本身 */
    padding: 0;
    /* 根据需要调整内边距以适应图像 */
}

.button-with-image .button-image {
    max-width: 100%;
    /* 限制图像的最大宽度 */
    max-height: 100%;
    /* 限制图像的最大高度 */
    display: block;
    /* 避免底部的空白间隙 */
    border-radius: 50%;
    /* 使图像显示为圆形 */
}
</style>